<template>

    <a-form ref="formRef" name="custom-validation" :model="formState" v-bind="layout" @finish="handleFinish">
        <a-row>

            <a-col :span="4">
                <a-form-item has-feedback label="角色名称" name="role_name">
                    <a-input allowClear v-model:value="formState.role_name" />
                </a-form-item>
            </a-col>

            <a-col :span="4">
                <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
                    <a-button type="primary" html-type="submit">查询</a-button>
                    <!-- <a-button type="primary" style="margin-left: 10px" @click="handleAdd">新增</a-button> -->
                </a-form-item>
            </a-col>
        </a-row>

        <a-row>
            <a-col :span="24">
                <a-flex justify="flex-end">
                    <a-button type="primary" style="margin-left: 10px" @click="handleAdd">新增</a-button>
                </a-flex>
            </a-col>
        </a-row>
    </a-form>


    <a-row>
        <a-col :span="24">
            <a-table size="small" style="width: 100%;" :columns="columns" :data-source="data">
                <template #bodyCell="{ column, text, record }">
                    <template v-if="column.dataIndex === 'name'">
                        <a>{{ text }}</a>
                    </template>
                    <template v-if="column.dataIndex === 'action'">
                        <a @click="handleEdit(record)">编辑</a>
                        <a @click="handleDelete(record)">删除</a>
                    </template>
                </template>
            </a-table>
        </a-col>
    </a-row>

    <a-row>
        <a-drawer size="large" v-model:open="open" class="custom-class" root-class-name="root-class-name"
            style="color: red" :title="addFormState.role_id ? '编辑' : '新增'" placement="right">
            <a-form :rules="addRulesForm" ref="addFormRef" name="custom-validation" :model="addFormState"
                v-bind="layout" @finish="addFormState.role_id ? handleEditFinish($event) : handleAddFinish($event)">

                <a-form-item has-feedback label="角色名称" name="role_name">
                    <a-input v-model:value="addFormState.role_name" />
                </a-form-item>

                <a-form-item has-feedback label="权限内容" name="permissions">
                    <a-tree defaultExpandAll v-model:checkedKeys="addFormState.permissions" checkable
                        :tree-data="treeData" :field-names="{ title: 'name', key: 'key', children: 'child' }"
                        @check="handleTreeCheck">

                    </a-tree>
                </a-form-item>


                <a-form-item has-feedback>
                    <a-col :span="24">
                        <a-flex justify="flex-end">
                            <a-button type="primary" style="margin-left: 10px" html-type="submit">保存</a-button>
                        </a-flex>
                    </a-col>
                </a-form-item>
            </a-form>
        </a-drawer>
    </a-row>
</template>
<script setup>
import { reactive, ref } from 'vue';
import service from '@/api/modulesApi/role';
import { message } from 'ant-design-vue';

const columns = [
    {
        title: '角色编号',
        dataIndex: 'role_id',
        key: 'role_id',
    },
    {
        title: '角色名称',
        dataIndex: 'role_name',
        key: 'role_name',
    },
    {
        title: '权限分配',
        dataIndex: 'permissions',
        key: 'permissions',
    },
    {
        title: '操作',
        dataIndex: 'action',
        key: 'action',
    },
];
const data = ref();
const treeData = ref(
    []
);
const formRef = ref();
const formState = reactive({
    role_name: '',
});

const open = ref(false);

const addFormState = reactive({
    role_id: '',
    role_name: '',
    permissions: [],
});
const addFormRef = ref();

const addRulesForm = {
    role_name: [{ required: true, message: '请输入角色名称' }],
    permissions: [{ required: true, message: '请输入权限内容' }],
};

const handleAdd = () => {
    open.value = true;
    addFormState.role_id = ''
    addFormState.role_name = ''
    addFormState.permissions = []
};

const handleAddFinish = async (values) => {
    await service.addRole(values)
    message.success('新增成功')
    getRole()
    addFormRef.value.resetFields();
    open.value = false;
};

const handleEditFinish = async (values) => {
    values.role_id = addFormState.role_id
    await service.updateRole(values)
    message.success('编辑成功')
    getRole()
    addFormRef.value.resetFields();
    open.value = false;
}

const handleEdit = (record) => {
    console.log(record);
    addFormState.role_id = record.role_id
    addFormState.role_name = record.role_name
    addFormState.permissions = record.permissions.split(',')
    open.value = true;
}

const handleDelete = async (record) => {
    await service.deleteRole({ role_id: record.role_id })
    message.success('删除成功')
    getRole()
}

const layout = {
    labelCol: { span: 7 },
    wrapperCol: { span: 14 },
};

const handleFinish = async (values) => {
    await getRole()
};

// 处理树形组件选择，只保留叶子节点
const handleTreeCheck = (checkedKeys, info) => {
    console.log('checkedKeys:', checkedKeys, 'info:', info)

    // 获取所有叶子节点的key
    const leafKeys = getLeafKeys(treeData.value)

    // 获取所有选中的叶子节点
    const selectedLeafKeys = checkedKeys.filter(key => leafKeys.includes(key))

    // 获取所有选中的父节点，并获取其所有子节点
    const parentKeys = checkedKeys.filter(key => !leafKeys.includes(key))
    const childKeys = []

    parentKeys.forEach(parentKey => {
        const children = getChildrenKeys(parentKey, treeData.value)
        childKeys.push(...children)
    })

    // 合并所有叶子节点，去重
    const finalKeys = [...new Set([...selectedLeafKeys, ...childKeys])]

    console.log('选中的叶子节点:', selectedLeafKeys)
    console.log('父节点对应的子节点:', childKeys)
    console.log('最终保存的叶子节点:', finalKeys)

    // 更新选中状态（只保存叶子节点）
    addFormState.permissions = finalKeys
}

// 获取指定节点的所有子节点key
const getChildrenKeys = (parentKey, treeData) => {
    const childrenKeys = []
    const findChildren = (nodes, targetKey) => {
        nodes.forEach(node => {
            if (node.key === targetKey) {
                if (node.child && node.child.length > 0) {
                    node.child.forEach(child => {
                        if (!child.child || child.child.length === 0) {
                            // 这是叶子节点
                            childrenKeys.push(child.key)
                        } else {
                            // 这是中间节点，递归获取其所有叶子节点
                            const grandChildren = getChildrenKeys(child.key, [child])
                            childrenKeys.push(...grandChildren)
                        }
                    })
                }
            } else if (node.child && node.child.length > 0) {
                findChildren(node.child, targetKey)
            }
        })
    }

    findChildren(treeData, parentKey)
    return childrenKeys
}

// 递归获取所有叶子节点的key
const getLeafKeys = (treeData) => {
    const leafKeys = []

    const traverse = (nodes) => {
        nodes.forEach(node => {
            if (!node.child || node.child.length === 0) {
                // 这是叶子节点
                leafKeys.push(node.key)
            } else {
                // 这是父节点，继续遍历子节点
                traverse(node.child)
            }
        })
    }

    traverse(treeData)
    return leafKeys
}

// 测试函数：验证逻辑
const testTreeLogic = () => {
    const leafKeys = getLeafKeys(treeData.value)
    console.log('所有叶子节点:', leafKeys)

    // 测试选中"客户管理"父节点
    const testCheckedKeys = ['客户管理']
    const parentKeys = testCheckedKeys.filter(key => !leafKeys.includes(key))
    const childKeys = []

    parentKeys.forEach(parentKey => {
        const children = getChildrenKeys(parentKey, treeData.value)
        childKeys.push(...children)
    })

    console.log('测试选中"客户管理"的结果:', childKeys)
}

const getRole = async () => {
    const res = await service.getRole(formState)
    data.value = res.data
}
getRole()


// 获取权限分配
const getPermissions = async () => {
    const res = await service.getPermissions()
    treeData.value = res.data
}
getPermissions()
</script>
